/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.facedoor.modular.devicebase.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.annotion.DataScope;
import vip.xiaonuo.core.annotion.Permission;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.base.param.BaseParam;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.param.DeviceBaseParam;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.devicebase.vo.StatisticsVo;
import vip.xiaonuo.facedoor.modular.devicebase.vo.lock.LockCell;
import vip.xiaonuo.facedoor.modular.devicebase.vo.lock.LockCellState;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;
import vip.xiaonuo.sys.modular.org.param.SysOrgParam;
import vip.xiaonuo.sys.modular.org.service.SysOrgService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 终端基础属性表控制器
 *
 * @author 胡鹏达
 * @date 2022-07-08 15:24:36
 */
@RestController
@Api(value = "设备基础文档")
public class DeviceBaseController {

    @Resource
    private DeviceBaseService deviceBaseService;

    @Resource
    private SysOrgService sysOrgService;


    @Resource
    private MemberUserService memberUserService;

    @Resource
    private VisitorService visitorService;


    /**
     * 删除系统组织机构
     *
     * @author xuyuxiang
     * @date 2020/3/25 14:54
     */
    @DataScope
    @PostMapping("/sysOrg/delete")
    @BusinessLog(title = "系统组织机构_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody @Validated(BaseParam.delete.class) List<SysOrgParam> sysOrgParamList) {
        long count = memberUserService.count(new LambdaQueryWrapper<MemberUser>().in(MemberUser::getOrgId, sysOrgParamList.stream().map(SysOrgParam::getId).collect(Collectors.toList())));
        if (count != 0) {
            throw new ServiceException(500, "该组织下还有人员!");
        }

        long visitorCount = visitorService.count(new LambdaQueryWrapper<Visitor>().in(Visitor::getOrgId, sysOrgParamList.stream().map(SysOrgParam::getId).collect(Collectors.toList())));
        if (visitorCount != 0) {
            throw new ServiceException(500, "该组织下还有人员!");
        }
        sysOrgService.delete(sysOrgParamList);
        return new SuccessResponseData();
    }

    @PostMapping("/deviceBase/openDoor")
    public ResponseData openDoor(@RequestBody DeviceBaseParam deviceBaseParam) {
        deviceBaseService.openDoor(deviceBaseParam);
        return new SuccessResponseData();
    }


    @ApiOperation(value = "首页统计接口", tags = "首页统计接口", response = StatisticsVo.class)
    @GetMapping("/deviceBase/statistics")
    public ResponseData statistics() {
        return new SuccessResponseData(deviceBaseService.statistics());
    }

    @Permission
    @GetMapping("/deviceBase/page")
    @BusinessLog(title = "终端基础属性表_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData page(DeviceBaseParam deviceBaseParam) {
        return new SuccessResponseData(deviceBaseService.page(deviceBaseParam));
    }


    @Permission
    @GetMapping("/listRemotePerson/page")
    @BusinessLog(title = "终端基础属性表_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData listPerson(DeviceBaseParam deviceBaseParam) {
        return new SuccessResponseData(deviceBaseService.listPerson(deviceBaseParam.getId(), deviceBaseParam.getName()));
    }


    @Permission
    @PostMapping("/deviceBase/add")
    @BusinessLog(title = "终端基础属性表_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData add(@RequestBody @Validated(DeviceBaseParam.add.class) DeviceBaseParam deviceBaseParam) {
        deviceBaseService.add(deviceBaseParam);
        return new SuccessResponseData();
    }

    @Permission
    @PostMapping("/deviceBase/delete")
    @BusinessLog(title = "终端基础属性表_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody @Validated(DeviceBaseParam.delete.class) DeviceBaseParam deviceBaseParam) {
        deviceBaseService.delete(deviceBaseParam);
        return new SuccessResponseData();
    }

    @Permission
    @PostMapping("/deviceBase/edit")
    @BusinessLog(title = "终端基础属性表_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData edit(@RequestBody @Validated(DeviceBaseParam.edit.class) DeviceBaseParam deviceBaseParam) {
        deviceBaseService.edit(deviceBaseParam);
        return new SuccessResponseData();
    }


    @Permission
    @GetMapping("/deviceBase/detail")
    @BusinessLog(title = "终端基础属性表_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(@Validated(DeviceBaseParam.detail.class) DeviceBaseParam deviceBaseParam) {
        return new SuccessResponseData(deviceBaseService.detail(deviceBaseParam));
    }

    @Permission
    @GetMapping("/deviceBase/list")
    @BusinessLog(title = "终端基础属性表_列表", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(DeviceBaseParam deviceBaseParam) {
        return new SuccessResponseData(deviceBaseService.list(deviceBaseParam));
    }

    @Permission
    @GetMapping("/deviceBase/cellState")
    @BusinessLog(title = "存储柜柜格状态_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData getCellState(DeviceBaseParam deviceBaseParam) {
        return new SuccessResponseData(deviceBaseService.getCellState(deviceBaseParam));
    }


    @Permission
    @GetMapping("/deviceBase/cellStateException")
    @BusinessLog(title = "存储柜柜格状态_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData cellStateException(@RequestParam Long id) {
        Map<Integer, LockCell> result = new HashMap<>();
        DeviceBase deviceBase = deviceBaseService.getById(id);
        String lockCellState = deviceBase.getLockCellState();
        if (StringUtils.isNotBlank(lockCellState)) {
            List<LockCell> stateList = JSON.parseArray(lockCellState, LockCell.class);
            if (CollectionUtils.isNotEmpty(stateList)) {
                List<LockCell> lockCells = stateList.stream().filter(x -> ObjectUtil.equal(x.getS(), 0)).collect(Collectors.toList());
                for (LockCell lockCell : lockCells) {
                    result.put(deviceBase.getRowNum() * (lockCell.getY() - 1) + lockCell.getX(), lockCell);
                }
            }
        }
        return new SuccessResponseData(result);
    }

    @PostMapping("/deviceBaseLocker/import")
    @BusinessLog(title = "存储柜人员_导入", opType = LogAnnotionOpTypeEnum.IMPORT)
    public ResponseData deviceBaseLocker(@RequestPart("file") MultipartFile file) {
        return ResponseData.success(deviceBaseService.importExcel(file));
    }

    @PostMapping("/deviceBase/deviceUpdatePush")
    public ResponseData deviceUpdatePush(@RequestBody DeviceBaseParam param){
        deviceBaseService.deviceUpdatePush(param);
        return ResponseData.success();
    }


}
